package com.zut.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zut.common.BaseContext;
import com.zut.common.R;
import com.zut.entity.AddressBook;
import com.zut.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;


    @GetMapping("/list")
    public R<List<AddressBook>> list(){
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<AddressBook> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AddressBook::getUserId,userId);
        lambdaQueryWrapper.orderByDesc(AddressBook::getIsDefault);
        lambdaQueryWrapper.orderByDesc(AddressBook::getCreateTime);
        return R.success(addressBookService.list(lambdaQueryWrapper));

    }
    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id){
        return R.success(addressBookService.getById(id));
    }


   @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){

            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookService.save(addressBook);

        return R.success("添加成功");
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
   @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook){
        addressBookService.setDefault(addressBook);
        return R.success("修改成功");
    }
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        lambdaQueryWrapper.eq(AddressBook::getIsDefault,1);
        return R.success(addressBookService.getOne(lambdaQueryWrapper));
    }


}
